#include <iostream>
#include "nasm/symbol/symbolTable.h"

namespace dspnasm{
    void SymbolTable::addSymbol(std::shared_ptr<Symbol> symbol) {
        if (!existSymbol(symbol->m_symbolName)) {
            m_symbolTable[symbol->m_symbolName] = symbol;
        } else {
            // 本地符号覆盖外部符号
            if (m_symbolTable[symbol->m_symbolName]->m_isExterned && !symbol->m_isExterned) {
                m_symbolTable[symbol->m_symbolName] = symbol;
            }else if(m_symbolTable[symbol->m_symbolName]->m_isGlobal){
                symbol->m_isGlobal = true;
                m_symbolTable[symbol->m_symbolName] = symbol;
            }
        }
    }

    std::shared_ptr<Symbol> SymbolTable::getSymbol(const std::string &symbolName) {
        if (existSymbol(symbolName)) {
            return m_symbolTable[symbolName];
        }
        return nullptr;
    }

    void SymbolTable::printSymbol() const {
        for (auto &symbol: m_symbolTable) {
            std::cout << symbol.second->toString() << std::endl;
        }
    }

    bool SymbolTable::existSymbol(const std::string &symbolName) {
        return m_symbolTable.find(symbolName) != m_symbolTable.end();
    }

    void SymbolTable::exportSymbols(std::shared_ptr<ElfFile> elfFile) {
        for (auto &symbol: m_symbolTable) {
            if (!symbol.second->m_isEqu) {
                elfFile->addSymbol(symbol.second);
            }
        }
    }
}
